﻿using System;
using System.Collections.ObjectModel;
using System.Linq;

using TraceView.Shared.Handlers.DefaultHandler;

namespace TraceView.Shared
{
    public interface ITraceHandler
    {
        TraceObject Serialize(object instance);
        IBaseHandlerView GetView(TraceData traceData);
    }

    public interface IBaseHandlerView
    {
        bool ContainsSearchText(string searchText);
        string Copy();
        string GetToastString();
    }

    public sealed class RegisteredTraceHandler
    {
        private readonly ITraceHandler _handler;
        private readonly string _type;

        public RegisteredTraceHandler(string type, ITraceHandler handler)
        {
            if (type == null) throw new ArgumentNullException("type");
            if (handler == null) throw new ArgumentNullException("handler");
            _type = type;
            _handler = handler;
        }

        public string Type
        {
            get { return _type; }
        }

        public ITraceHandler Handler
        {
            get { return _handler; }
        }
    }

    public sealed class RegisteredTraceHandlers : KeyedCollection<string, RegisteredTraceHandler>
    {
        private static readonly RegisteredTraceHandlers _instance = new RegisteredTraceHandlers();

        static RegisteredTraceHandlers()
        {
            _instance.Add(new RegisteredTraceHandler(typeof (String).ToString(), new DefaultTraceHandler()));
        }

        private RegisteredTraceHandlers()
        {
        }

        public new RegisteredTraceHandler this[string key]
        {
            get
            {
                if (Dictionary != null)
                {
                    RegisteredTraceHandler handler;
                    return Dictionary.TryGetValue(key, out handler) ? handler : null;
                }
                return this.FirstOrDefault(item => item.Type.Equals(key, StringComparison.Ordinal));
            }
        }

        public static RegisteredTraceHandlers Instance
        {
            get { return _instance; }
        }

        protected override string GetKeyForItem(RegisteredTraceHandler item)
        {
            return item.Type;
        }

        protected override void InsertItem(int index, RegisteredTraceHandler item)
        {
            //TODO
            base.InsertItem(index, item);
        }

        protected override void SetItem(int index, RegisteredTraceHandler item)
        {
            throw new InvalidOperationException();
        }
    }
}